<template>
  <div class="app-container">
    <div class="mainbox">
      <div class="filter-container">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams"
                 :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="功能名称" prop="functionName">
            <el-input
              v-model.trim="queryParams.functionName"
              :maxlength="7"
              placeholder="请输入功能名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="应用名称" prop="appCode">
            <el-cascader
              v-model="queryParams.appCode"
              :options="thirdOptions"
              placeholder="请选择应用名称"
              size="small"
              :props="{
                value:'appCode',
                label:'name'
              }"
              filterable
            />
            <!-- <el-select v-model="queryParams.appCode" filterable placeholder="请选择应用名称" size="small">
              <el-option
                v-for="dict in thirdOptions"
                :key="dict.appCode"
                :label="dict.name"
                :value="dict.appCode"
              />
            </el-select> -->
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <div>
          <div class="flex-1" />
          <div style="display:flex;">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>
      <dt-table
        ref="treeTable"
        v-loading="loading"
        :table-opts="tableOpts"
        row-key="functionId"
        @pagination="getList"
        @handleSelectionChange="handleSelectionChange"
      >
        <template #toolbarBtn>
          <el-dropdown style="margin-left: 10px;">
            <el-button
              v-permission="['THREEFUNCTION_EXPORT_BUTTON']"
              :disabled="tableOpts.tableData.length<=0"
              size="medium"
            >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
              <el-dropdown-item
                @click.native="handleDownload('all')"
              >导出所有</el-dropdown-item>
              <el-dropdown-item
                @click.native="handleDownload()"
              >导出选中</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button v-permission="['THREEFUNCTION_IMPORT_BUTTON']" style="margin-left: 10px" @click="handleImport">导入</el-button>
        </template>
      </dt-table>
    </div>
    <threeAppDialog ref="thirdApp" :third-options="thirdOptions" @getList="getList" />
    <dtDialog
      title="功能导入"
      :visible.sync="fileUploadVisible"
      width="620px"
      :is-loading="uploadLoading"
      @closeDialog="fileUploadVisible = false"
      @comfirmBtn="importDataSave"
    >
      <el-form slot="content">
        <div class="">
          <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" />
        </div>
      </el-form>
    </dtDialog>
  </div>
</template>

<script>
import threeAppDialog from './components/threeAppDialog'
import { exportExcel, getAppServiceList, getAppList, removeFunction, importFunction, templateFile, updateStatus } from '@/framework/api/threeFunction/index'

export default {
  name: 'ThreeFunction',
  components: { threeAppDialog },
  data() {
    return {
      handleImportTemplate: templateFile,
      fileUploadVisible: false,
      uploadLoading: false,
      total: 0,
      // 显示搜索条件
      showSearch: true,
      multipleSelection: [],
      // 查询参数
      queryParams: {
        functionName: null,
        appCode: null
      },
      thirdOptions: [],
      loading: false,
      tableOpts: {
        rowKey: 'functionId',
        toolbarBtn: [
          {
            label: '新增',
            permission: ['THREEFUNCTION_ADD_BUTTON'],
            type: 'primary',
            icon: 'el-icon-plus',
            click: () => {
              this.handleAdd()
            }
          }
        ],
        tableData: [],
        firstTableCol: {
          select: true
        },
        tableCol: [
          {
            prop: 'functionName',
            label: '功能名称',
            show: true
          },
          {
            prop: 'functionCode',
            label: '功能编号',
            show: true
          },
          {
            prop: 'appName',
            label: '应用名称',
            show: true
          },
          {
            prop: 'routerAddress',
            label: '路由地址',
            show: true
          },
          {
            prop: 'sort',
            label: '排序',
            show: true
          },
          // {
          //   prop: 'serviceName',
          //   label: '所属服务',
          //   show: true
          // },
          {
            prop: 'statusFlag',
            label: '是否启用',
            show: true,
            type: 'switch',
            activeValue: 1,
            inactiveValue: 2,
            switchChange: (row, value) => { return this.statusFlag(row) }
          }
        ],
        operator: {
          width: 292,
          operatorBtn: [
            {
              text: '修改',
              permission: ['THREEFUNCTION_UPDATE_BUTTON'],
              size: 'small',
              icon: 'el-icon-edit',
              click: (row, col, cellValue) => { return this.editUserInfo(row) }
            },
            {
              text: '删除',
              permission: ['THREEFUNCTION_DEL_BUTTON'],
              size: 'small',
              icon: 'el-icon-delete',
              type: 'danger',
              click: (row, col, cellValue) => { return this.removeUser(row) },
              disabledChange: (row) => { return row.children && row.children.length > 0 }
            }
          ]
        }
      }
    }
  },
  watch: {
    fileUploadVisible: {
      handler(n, o) {
        if (!n) {
          this.$nextTick().then(() => {
            this.$refs.dtImportFileRef.fileList = []
          })
        }
      }
    }
  },
  created() {
    this.getAppOptions()
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      importFunction(formData).then(async (res) => {
        this.uploadLoading = true
        this.fileUploadVisible = false
        if (res.data.errorDownloadPath) {
          this.$alert(`<div> <div class="title">${res.data.tip}</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败三方功能信息</span> </div> </div>`, '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert(`<div> <div class="title">${res.data.tip}导入完成`, {
            dangerouslyUseHTMLString: true
          })
        }
        this.getList()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function () {
          window.location.href = res.data.errorDownloadPath
        }
        this.uploadLoading = false
      }).catch((res) => {
        this.uploadLoading = false
      })
    },
    editUserInfo(row) {
      this.$refs.thirdApp.openDialog('update', row)
    },
    removeUser(row) {
      this.$dtModal.confirm(`是否确认删除应用名称为"${row.appName}"的数据项？`).then(() => {
        return removeFunction({
          functionId: row.functionId
        })
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
        // 解决勾选了一个数据后，再删除该数据，然后再进行导出的时候导出不提示"至少勾选一条数据"，并且可以导出导出的表为空的bug
        this.multipleSelection.forEach((item, index, multipleSelection) => {
          if (item.functionId === row.functionId) {
            multipleSelection.splice(index, 1)
            return multipleSelection
          } else {
            return multipleSelection
          }
        })
      }).catch(() => {})
    },
    handleImport() {
      this.fileUploadVisible = true
    },
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        if (!this.queryParams.appCode) {
          this.$dtMessage({
            title: '失败',
            message: '请选择应用',
            type: 'error',
            duration: 2000
          })
          return
        }
        con = {
          allFunction: true,
          appCode: this.queryParams.appCode[1]
        }
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请先选择要批量处理的数据',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map((res) => {
          return res.functionId
        }).join(',')
        con = {
          functionIdList: ids,
          // positionName: this.queryParams.positionName,
          allFunction: false
        }
      }
      this.showScreenLoading()
      exportExcel(con).then((res) => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const objectUrl = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = objectUrl // 指定下载链接
        a.download = '三方功能菜单' // 指定下载文件名
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL对象
        this.hideScreenLoading()
      }).catch((res) => {
        this.hideScreenLoading()
      })
    },
    handleAdd() {
      console.log(this.queryParams.appCode)
      if (!this.queryParams.appCode) {
        this.$dtMessage({
          title: '失败',
          message: '请选择应用',
          type: 'error',
          duration: 2000
        })
        return
      }
      this.$refs.thirdApp.openDialog('create', { appCode: this.queryParams.appCode[1] })//
    },
    getAppOptions() {
      getAppList().then(({ data: response }) => {
        this.thirdOptions = response
        if (response && response.length) {
          this.queryParams.appCode = [response[0].appCode, response[0].children[0].appCode]
          this.getList()
        }
      })
    },
    getList() {
      this.loading = true
      if (!this.queryParams.appCode) {
        this.$dtMessage({
          title: '失败',
          message: '请选择应用',
          type: 'error',
          duration: 2000
        })
        this.loading = false
        return
      }
      getAppServiceList({ ...this.queryParams, appCode: this.queryParams.appCode[1] }).then(({ data: response }) => {
        this.tableOpts.tableData = response
        this.loading = false
      })
    },
    handleQuery() {
      this.getList()
    },
    handleReset() {
      // const { appCode } = this.queryParams
      this.resetForm('queryForm')
      const temp = this.thirdOptions
      this.queryParams = {
        appCode: temp.length > 0 ? [temp[0].appCode, temp[0].children[0].appCode] : null
      }
      this.handleQuery()
    },
    statusFlag(row) {
      const param = {
        functionId: row.functionId, statusFlag: row.statusFlag
      }
      updateStatus(param).then((res) => {
        this.$dtMessage({
          type: 'success',
          message: '状态修改成功'
        })
        this.getList()
      }).catch(() => {
        this.getList()
      })
    }
  }
}
</script>

<style type="text/css" scoped>
</style>
